require 'crack'

=begin
  This class provides the main gadget server interface.
=end
class GadgetController < ApplicationController
  
  # Retrieve gadget metadata
  def metadata
    json = params[:json]
    param_str = Crack::JSON.parse(json)
    @context = param_str['context']
    @gadgets = param_str['gadgets']
    
    @gadgets_results = []
    @gadgets.each do |gadget|
      url = gadget['url']  
      @xml_spec = XmlSpec.new
      @xml_spec.read(url)
      @gadgets_results.push(@xml_spec.metadata(@context['container'], 
                                               @context['view'],
                                               @context['language'], 
                                               @context['country'],
                                               gadget['moduleId']))
    end    
    @metadata_result = {'gadgets' => @gadgets_results}
    
    render :json => @metadata_result.to_json
  end
  
  
  # Render a gadget
  # returns the gadget's HTML content plus gadget and opensocial JavaScript API
  # below is sample of the st parameter:
=begin
  st  john.doe:john.doe:7810:shindig:http%3A//localhost%3A8080/gadgets/files/samplecontainer/examples/SocialHelloWorld.xml:0:default
=end
  def ifr
    @container = params[:container]
    @country = params[:country]
    @lang = params[:lang]
    @mid = params[:mid]
    @nocache = params[:nocache]
    @parent = params[:parent]
    @st = params[:st]
    @url = params[:url]
    @view = params[:view]
    
    gadget = Gadget.new(@url)
    @content = gadget.render(@view) 
    render :template=>'gadget/ifr', :layout=>false
  end
  
  
  # Serves as a proxy for gadgets making requests to remote services
  def makeRequest
    url = params[:url]
    content_type = params[:CONTENT_TYPE]
    authorization = params[:AUTHORIZATION]
    oauth_service_name = params[:OAUTH_SERVICE_NAME]
    method = params[:METHOD]

    req = RemoteRequest.new(url, method, content_type, authorization, oauth_service_name)
    response = req.process
    
    render :json, response
  end

  
end


